package com.geeke.sys.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;

import com.geeke.common.service.CrudService;
import com.geeke.common.data.PageRequest;
import com.geeke.common.data.Parameter;
import com.geeke.config.exception.CommonJsonException;

import com.geeke.sys.dao.DictItemDao;
import com.geeke.sys.entity.DictItem;
import com.geeke.utils.ResultUtil;
import com.geeke.utils.constants.ErrorEnum;
import com.google.common.collect.Lists;

/**
 * 字典项表 Service
 * @author
 * @version
 */
@Service("dictItemService")
@Transactional(readOnly = true)
public class DictItemService extends CrudService<DictItemDao, DictItem> {

    @Transactional(readOnly = false)
    @Override
    public DictItem save(DictItem dictItem) {
        // 重复性检查
        List<Parameter> params = Lists.newArrayList();
        // 字典项值在同一个字典类型下不能重复
        params.clear();
        params.add(new Parameter("dictItem.dict_type_id", "=", dictItem.getDictType().getId()));
        params.add(new Parameter("dictItem.value", "=", dictItem.getValue()));
        params.add(new Parameter("dictItem.del_flag", "=", dictItem.getDelFlag()));

        if(!StringUtils.isBlank(dictItem.getId())) {
          params.add(new Parameter("dictItem.id", "<>", dictItem.getId()));
        }

        if(this.dao.count(new PageRequest(params)) > 0) {
            throw new CommonJsonException(ResultUtil.warningJson(ErrorEnum.E_50001, "同一字典类型下已存在相同字典项值"));
        }

        return super.save(dictItem);
    }
} 